package com.apache.portal.service.plugin;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.AnntationBean;
import com.apache.portal.common.enums.WcmMethodEnum;
import com.apache.portal.common.template.CreateTableSql;
import com.apache.portal.common.template.FreemarkerHelper;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.portal.filter.KeywordFilter;
import com.apache.portal.thread.FileOperateUtil;
import com.apache.rpc.common.LoadRpcService;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.ConfigUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import com.apache.website.entity.Channel;
import com.apache.website.entity.Manuscript;
import com.apache.website.entity.ManuscriptVo;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xhe
 * 对接cms-Webiste插件
 */
@AnntationBean(name = "wcm")
    public class WebSiteSystemPluginImpl implements PortalPlugin {

    private Logger log = LoggerFactory.getLogger(getClass());

    /* (non-Javadoc)
     * @see com.apache.portal.plugin.PortalPlugin#doInvoke(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.Map)
     */
    public Object doInvoke(HttpServletRequest request, HttpServletResponse response,
            Map<String, String> params) {
        String doCode = params.get("doCode");
        log.info("cms单独处理业务[doCode]->"+doCode);
        LoginUser loginUser = PortalPubFactory.getInstance().getLoginUser(request);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.putAll(params);
        ResultEntity entity = new ResultEntity();
        ResultMsg msg = null;
        switch (WcmMethodEnum.getName(doCode)) {
        case channles://栏目列表 doCode=cllist
            paramsMap = toMapDelNull(paramsMap);
            if (ToolsUtil.isNotNull(String.valueOf(paramsMap.get("rows")))) {
                paramsMap.put("pageSize", paramsMap.get("rows"));
                paramsMap.put("pageIndex", paramsMap.get("page"));
            }
            //调用RPC
            entity = (ResultEntity) getRpcResult("channelList", paramsMap);
            break;
        case channel://获取栏目信息doCode=clview
            entity = (ResultEntity) getRpcResult("channelEntity", paramsMap);
            break;
        case manuscripts://稿件列表doCode=mtlist
            if (ToolsUtil.isNotNull(String.valueOf(paramsMap.get("rows")))) {
                paramsMap.put("pageSize", paramsMap.get("rows"));
                paramsMap.put("pageIndex", paramsMap.get("page"));
            }
            entity = (ResultEntity) getRpcResult("manuscriptList", paramsMap);
            break;
        case manuscript://查看稿件doCode=mtview
            entity = (ResultEntity) getRpcResult("manuscriptEntity", paramsMap);
            break;
        case clOneMt://启动项目流程doCode=oneinfo
            entity = (ResultEntity) getRpcResult("clOneMt", paramsMap);
            break;
        case saveChannel://保存栏目信息doCode=saveChannel
            entity = (ResultEntity) getRpcResult("saveChannel", paramsMap);
            if (null != entity.getEntity()) {
                msg = new ResultMsg("T", "保存栏目成功");
            } else {
                msg = new ResultMsg("F", "保存栏目失败：" + entity.getMessage());
            }
            return msg;
        case saveManuscript://保存稿件信息doCode=saveArtice
            paramsMap.remove("editorValue");
            entity = (ResultEntity) getRpcResult("saveManuscript", paramsMap);
            if (null != entity.getEntity()) {
                msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
            } else {
                msg = new ResultMsg("F", "保存稿件失败："+entity.getMessage());
            }
            return msg;
        case delChannel://删除栏目信息doCode=dealChannel
            entity = (ResultEntity) getRpcResult("delChannel", paramsMap);
            if (null != entity.getEntity()) {
                msg = new ResultMsg("T", "删除栏目成功");
            } else {
                msg = new ResultMsg("F", entity.getMessage());
            }
            return msg;
        case delManuscript://删除稿件信息doCode=delArtice
            entity = (ResultEntity) getRpcResult("delManuscript", paramsMap);
            if (null != entity.getEntity()) {
                msg = new ResultMsg("T", "删除稿件成功");
            } else {
                msg = new ResultMsg("F", entity.getMessage());
            }
            return msg;
        case publishArtice://发布稿件doCode=publishArtice
            msg = publishArtice(request, paramsMap);
            return msg;
        case preViewAritce://预览稿件doCode=preArtice
            msg = preViewAritce(request, paramsMap);
            return msg;
        case unpublishArtice://撤销发布稿件doCode=unpublishArtice
            msg = unpublishArtice(request, paramsMap);
            return msg;
        case pushArticeToChannel:
            msg = pushArticeToChannel(request, paramsMap);
            return msg;
        }
        return entity;
    }

    /**
     * description:  发布稿件
     */
    private ResultMsg publishArtice(HttpServletRequest request, Map<String, Object> paramsMap) {
        ResultMsg msg = new ResultMsg("T", "发布成功");
        log.info("正在发布稿件文章...");
        String filePath =
                ToolsUtil.getInstance().getLocalByKey("config.properties", "html_path")
                        + "/";
        String defStr = ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "wcm/");

        filePath = StrUtil.doNull(filePath, defStr);
        String manuscriptId = request.getParameter("manuscriptId");
        ResultEntity entity = (ResultEntity) getRpcResult("manuscriptEntity", paramsMap);
        if (null == entity.getEntity()) {
            msg = new ResultMsg("F", entity.getMessage());
            return msg;
        }
        ManuscriptVo mt = (ManuscriptVo) entity.getEntity();
        //补充发布时间参数值
        if(StrUtil.isNull(mt.getPublishedTime())){
            String publishedTime = DateUtils.Now.fmt_yyyyMMdd_HHmmss();
            mt.setPublishedTime(publishedTime);
        }
        paramsMap.put("channelId", mt.getChannelId());
        entity = (ResultEntity) getRpcResult("channelEntity", paramsMap);
        if (null == entity.getEntity()) {
            msg = new ResultMsg("F", "没有获取到栏目信息");
            return msg;
        }
        Channel channel = (Channel) entity.getEntity();
        Map<String, Object> data = new HashMap<String, Object>();
        String content = mt.getManuscriptContent();
        data.put("ctx", request.getContextPath());

        data.put("manuscript", mt);

        data.put("channel", channel);
        if (StrUtil.isNotNull(content)) {
            content = KeywordFilter.getInstance().doFilter(content);
        }
        String sysName = Validator.getDefaultStr(request.getParameter("sysName"), "cms");
        String parentId = String.valueOf(channel.getParentId());
        if (!"0".equals(parentId)) {
            //3、获取当前栏目同级兄弟栏目brother
            Map<String, Object> brotherChannelVo = new HashMap<String, Object>();
            brotherChannelVo.put("modelTypes", "s_tChannel");
            brotherChannelVo.put("tChannel.w_parentId", parentId);
            brotherChannelVo.put("orderBy", "channel_levels");
            brotherChannelVo.put("datasource", sysName);
            List brotherChannelList = (List) CreateTableSql.instance().init(brotherChannelVo);
            if (brotherChannelList == null || brotherChannelList.size() < 1) {
                log.error("未找父级栏目的兄弟栏目数据！");
            }
            data.put("brotherChannelList", brotherChannelList);

            //3.获取当前栏目父级栏目
            Map<String, Object> fatherChannelVo = new HashMap<String, Object>();
            fatherChannelVo.put("modelTypes", "s_tChannel");
            fatherChannelVo.put("tChannel.w_channelId", parentId);
            fatherChannelVo.put("datasource", sysName);
            List fatherChannelList = (List) CreateTableSql.instance().init(fatherChannelVo);
            if (fatherChannelList == null || fatherChannelList.size() < 1) {
                log.error("未找的父级栏目数据！");
            }
            Map<String, Object> fatherChannelData = new HashMap<String, Object>();
            fatherChannelData = (Map) fatherChannelList.get(0);
            data.put("fatherChannel", fatherChannelData);
        }
        data.put("manuscriptContent", content);
        boolean isNext = true;
        if("1".equals(mt.getType()) && ToolsUtil.isNotNull(mt.getUrl())){//普通文章必须判断url地址是否为空
            String htmlPath = filePath;
            if (!StrUtil.isNull(channel.getSiteCode())) {
                htmlPath += channel.getSiteCode() + "/html/";//发布到对于站点下
            }
            htmlPath += mt.getUrl();
            String ftlPath = "wcm/template/article.inc";
            String ifFontDesk = "";
            if (ToolsUtil.isNotNull(channel.getTempName())) {
                ftlPath = channel.getSiteCode() + "/template/" + channel.getTempName();
                ifFontDesk = "web";
            }
            log.info("正在发布:" + htmlPath);
            log.info("使用模板:" + ftlPath);
            boolean flag = FreemarkerHelper.instance()
                    .createHtml(ftlPath, data, htmlPath, ifFontDesk);
            if (!flag) {
                isNext = false;
                msg = new ResultMsg("F", "发布失败,请查看模板是否存在");
            }
        }
        if (isNext) {
            paramsMap.put("status", "2");
            paramsMap.put("publishedTime", mt.getPublishedTime());
            log.info("正在修改发布状态:"+paramsMap);
            getRpcResult("editManuscriptStatus", paramsMap);

            ///生成稿件json数据(仅首页用）
            if (StrUtil.isNotNull(mt.getWebsiteCode()) && StrUtil
                    .isNotNull(mt.getChannelCode())) {
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("pageSize", channel.getListMaxPage());
                paramMap.put("datasource",StrUtil.doNull(String.valueOf(paramsMap.get("datasource")), "cms"));
                if(paramsMap.containsKey("orderBy")){
                    paramMap.put("orderBy",paramsMap.get("orderBy"));
                }
                createManuscriptJson(mt, paramMap);
            }
        }
        log.info("发布稿件:" + JSONObject.fromObject(msg));
        return msg;
    }

    /**
     * 生成稿件json文件
     */
    private void createManuscriptJson(Manuscript manuscript, Map<String, Object> paramMap) {
        try {
            String filePath =
                    ToolsUtil.getInstance().getLocalByKey("config.properties", "html_path")
                            + "/";
            String defStr = filePath + manuscript.getWebsiteCode() + "/data/";
            Map<String, Object> bodyMap = new HashMap<String, Object>();
            String sysPass = ConfigUtil.getInstance().interfacePass();
            bodyMap.put("sysPass", sysPass);
            bodyMap.put("status", "2");
            bodyMap.put("channelId", manuscript.getChannelId());
            bodyMap.put("pageIndex", 1);
            bodyMap.put("Client-IP", paramMap.get("Client-IP"));
            bodyMap.put("datasource",
                    StrUtil.doNull(String.valueOf(paramMap.get("datasource")), "cms"));
            bodyMap.put("pageSize",
                    Validator.getDefaultStr(String.valueOf(paramMap.get("pageSize")), "100"));
            if(paramMap.containsKey("orderBy")){
                bodyMap.put("orderBy",paramMap.get("orderBy"));
            }else{
                bodyMap.put("orderBy","seq_num asc,published_Time desc,modify_time");
            }
            ResultEntity entity = (ResultEntity) getRpcResult("manuscriptList", bodyMap);
            Page pageList = (Page) entity.getEntity();
            if (ToolsUtil.isEmpty(pageList.getPageObjects())) {
                FileOperateUtil.newCreateFolder(defStr);
                String fileName = defStr + manuscript.getChannelCode() + ".json";
                boolean returnFalg = FileOperateUtil
                        .newCreateFile(fileName, "{\"total\":0,\"flag\":\"T\",\"rows\":[]}",
                                "UTF-8");
                log.info("数据文件生成：" + fileName + "   |   " + returnFalg);
                return;
            }
            List<Manuscript> list = pageList.getPageObjects();

            //			String defStr = ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "wcm/")
            //					+ manuscript.getWebsiteCode() + "/data/";

            Map<String, Object> data = new HashMap<String, Object>();
            List<Map> jlist = new ArrayList<Map>();
            data.put("total", pageList.getCount());
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                Manuscript mpt = list.get(i);
                map.put("title", mpt.getTitle());//标题
                map.put("subTitle", mpt.getSubTitle());//副标题
                map.put("shortTitle", mpt.getShortTitle());//短标题
                map.put("publishedTime", mpt.getPublishedTime());
                map.put("type", mpt.getType());
                map.put("websiteId", mpt.getWebsiteId());
                map.put("websiteCode", mpt.getWebsiteCode());
                map.put("channelCode", mpt.getChannelCode());
                map.put("redirectUrl", StrUtil.doNull(mpt.getRedirectUrl(), ""));//连接地址
                map.put("memo", StrUtil.doNull(mpt.getMemo(), ""));
                map.put("url", mpt.getUrl());
                jlist.add(map);
            }
            data.put("rows", jlist);
            JSONObject json = JSONObject.fromObject(data);
            FileOperateUtil.newCreateFolder(defStr);
            String fileName = defStr + manuscript.getChannelCode() + ".json";
            boolean returnFalg = FileOperateUtil.newCreateFile(fileName, json.toString(), "UTF-8");
            log.info("数据文件生成：" + fileName + "   |   " + returnFalg);
        } catch (Exception e) {

        }
    }

    /**
     * description:  预览稿件
     */
    private ResultMsg preViewAritce(HttpServletRequest request, Map<String, Object> paramsMap) {
        ResultMsg msg = new ResultMsg("F", "预览失败");
        ResultEntity entity = (ResultEntity) getRpcResult("manuscriptEntity", paramsMap);
        if (null == entity.getEntity()) {
            msg = new ResultMsg("F", entity.getMessage());
            return msg;
        }
        ManuscriptVo mt = (ManuscriptVo) entity.getEntity();
        paramsMap.put("channelId", mt.getChannelId());
        entity = (ResultEntity) getRpcResult("channelEntity", paramsMap);
        if (null == entity.getEntity()) {
            msg = new ResultMsg("F", "没有获取到栏目信息");
            return msg;
        }
        Channel channel = (Channel) entity.getEntity();
        Map<String, Object> data = new HashMap<String, Object>();
        String content = mt.getManuscriptContent();
        data.put("ctx", request.getContextPath());
        data.put("manuscript", mt);
        data.put("channel", channel);
        if (StrUtil.isNotNull(content))
            content = KeywordFilter.getInstance().doFilter(content);
        data.put("manuscriptContent", content);
        if (ToolsUtil.isNotNull(mt.getUrl())) {
            String ftlPath = "wcm/article.inc";
            String ifFontDesk = "";
            if (ToolsUtil.isNotNull(channel.getTempName())) {
                ftlPath = channel.getSiteCode() + "/template/" + channel.getTempName();
                ifFontDesk = "web";
            }
            try {
                String htmls = FreemarkerHelper.instance()
                        .getTemplateStr(data, ftlPath, ifFontDesk);
                msg = new ResultMsg("T", htmls);
            } catch (Exception e) {
                msg = new ResultMsg("F", "预览稿件失败,请查看模板是否存在");
            }
        }
        return msg;
    }

    /**
     * description:  撤销稿件
     */
    private ResultMsg unpublishArtice(HttpServletRequest request, Map<String, Object> paramsMap) {
        ResultMsg msg = new ResultMsg("T", "发布成功");
        paramsMap.put("status", "3");
        ResultEntity entity = getRpcResult("editManuscriptStatus", paramsMap);
        if ("true".equals(entity.getResult()) && StrUtil
                .isNotNull(String.valueOf(entity.getEntity()))) {
            String path = request.getParameter("url");
            String filePath = ToolsUtil.getClassLoaderPath().replaceAll("WEB-INF/classes/", "wcm/");
            FileOperateUtil.delFile(filePath + path);
            msg = new ResultMsg("T", "撤销成功");
            Map<String, Object> bodyMap = new HashMap<String, Object>();
            String sysPass = ConfigUtil.getInstance().interfacePass();
            bodyMap.put("sysPass", sysPass);
            bodyMap.put("manuscriptId", paramsMap.get("manuscriptId"));
            bodyMap.put("datasource",
                    StrUtil.doNull(String.valueOf(paramsMap.get("datasource")), "cms"));
            entity = (ResultEntity) getRpcResult("manuscriptEntity", bodyMap);
            ManuscriptVo mt = (ManuscriptVo) entity.getEntity();
            if (null != mt && StrUtil.isNotNull(mt.getWebsiteCode()) && StrUtil
                    .isNotNull(mt.getChannelCode())) {
                paramsMap.put("channelId", mt.getChannelId());
                entity = (ResultEntity) getRpcResult("channelEntity", paramsMap);
                if (null == entity.getEntity()) {
                    msg = new ResultMsg("F", "没有获取到栏目信息");
                    return msg;
                }
                Channel channel = (Channel) entity.getEntity();
                Map<String, Object> paramMap = new HashMap<String, Object>();
                paramMap.put("pageSize", channel.getListMaxPage());
                paramMap.put("datasource",
                        StrUtil.doNull(String.valueOf(paramsMap.get("datasource")), "cms"));
                createManuscriptJson(mt, paramMap);
            }
        } else {
            msg = new ResultMsg("F", "撤销失败");
        }
        return msg;
    }
    /**
     * description: 同步稿件到其他栏目内
     */
    private ResultMsg pushArticeToChannel(HttpServletRequest request, Map<String, Object> paramsMap) {
        ResultMsg msg = new ResultMsg("T", "同步稿件到其他栏目成功");
        ResultEntity entity = getRpcResult("pushArticeToChannel", paramsMap);
        if ("true".equals(entity.getResult()) && StrUtil
                .isNotNull(String.valueOf(entity.getEntity()))) {
           log.info("同步稿件到其他操作结果->"+JSONObject.fromObject(entity));
        } else {
            msg = new ResultMsg("F", "同步稿件到其他栏目失败");
        }
        return msg;
    }

    private ResultEntity getRpcResult(String methodKey, Map<String, Object> params) {
        InterfaceRegister ss = PortalPubFactory.getInstance().getRpcInfo("wcm");
//        ss.setAddress("");
        return LoadRpcService.service().doServiceClient("websiteService", methodKey, params, ss);
    }

    public Map<String, Object> toMapDelNull(Map<String, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (String key : map.keySet()) {
            if ("class".equals(key))
                continue;
            if (!StrUtil.isNull(String.valueOf(map.get(key))))
                result.put(key, map.get(key));
        }
        return result;
    }

}
